package 力扣_算法题综合.两数相加;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author zx
 * @create 2022-09-12 19:29
 */
public class 两数相加II {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Deque<Integer> stack1 = new ArrayDeque<>();
        Deque<Integer> stack2 = new ArrayDeque<>();
        while(l1 != null){
            stack1.push(l1.val);
            l1 = l1.next;
        }
        while(l2 != null){
            stack2.push(l2.val);
            l2 = l2.next;
        }
        int bit = 0;
        ListNode dummy = new ListNode(-1);
        ListNode temp = dummy;
        while(!stack1.isEmpty() || !stack2.isEmpty()){
            int a = stack1.isEmpty() ? 0 : stack1.pop();
            int b = stack2.isEmpty() ? 0 : stack2.pop();
            int sum = a + b + bit;
            temp.next = new ListNode(sum % 10);
            bit = sum / 10;
            temp = temp.next;
        }
        if(bit > 0){
            temp.next = new ListNode(bit);
        }
        return reverse(dummy.next);
    }
    private ListNode reverse(ListNode head){
        ListNode prev = null;
        while(head != null){
            ListNode temp = head.next;
            head.next = prev;
            prev = head;
            head = temp;
        }
        return prev;
    }
}
